package com.oj.interceptor;

import com.oj.config.OJConfig;
import com.oj.entity.User;
import com.oj.service.UserService;
import com.oj.util.IpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class AutoLoginInterceptor implements HandlerInterceptor {
    @Autowired
    private UserService userService;

    //Controller逻辑执行之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        try {
            // 记录本次访问的url
            request.getSession().setAttribute("session_url", request.getRequestURI());

            String ipAddress = IpUtil.getIpAddr(request);
            if (OJConfig.IsBlockIpList(ipAddress)) {
                //log.error(ipAddress + " is in black ip list. ==> " + request.getRequestURI());
                return false;
            }

            // 已经登录
            try {
                String username = request.getSession().getAttribute("session_username").toString();
                if (username != null) {
                    log.info(ipAddress + ": " + username + " ==> " + request.getRequestURI());
                    return true;
                }
            } catch (Exception e) {
            }

            // 流氓不遵守robots.txt协议
            if (request.getHeader("User-Agent").contains("YisouSpider") ||
                request.getHeader("User-Agent").contains("DataForSeoBot") ||
                request.getHeader("User-Agent").contains("Amazonbot")) {
                return false;
            }

            log.info(ipAddress + " - "+ request.getHeader("User-Agent") + ": ? ==> " + request.getRequestURI());

            Cookie[] cookies = request.getCookies();
            if (cookies == null) {
                return true;
            }

            String cookie_username = null;
            for (Cookie item : cookies) {
                if ("cookieOnlineJudgeUsername".equals(item.getName())) {
                    cookie_username = item.getValue();
                    break;
                }
            }

            String cookie_token = null;
            for (Cookie item : cookies) {
                if ("cookieOnlineJudgeToken".equals(item.getName())) {
                    cookie_token = item.getValue();
                    break;
                }
            }

            if (cookie_username == null || cookie_token == null) {
                return true;
            }

            User user = userService.query(cookie_username);
            if (user == null || user.getToken() == null || user.getToken().length() == 0) {
                return true;
            }

            if (cookie_token.equals(user.getToken())) {
                userService.login(request, response, user.getUsername(), user.getPassword());
            } else {
            }
        } catch (Exception e) {
            // TODO: handle exception
            log.error("AutoLoginInterceptor: Exception");
            return true;
        }

        return true;
    }

    //Controller逻辑执行完毕但是视图解析器还未进行解析之前
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    //Controller逻辑和视图解析器执行完毕
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
